package org.drl.tvkit.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @author LEE
 * @date:2011-7-19 上午11:43:08
 * 
 */

public class StringUtil {

	/**
	 * 
	 * @author LEE
	 * @date:2011-7-19 上午11:44:31 功能：检测字符串是否为空
	 * @param str
	 * @return
	 */
	public static boolean isNotNull(String str) {
		boolean result = false;
		if (str != null && !str.equals("") && !"null".equals(str)
				&& str.trim().length() > 0) {
			result = true;
		}
		return result;
	}

	public static boolean isNull(String str) {
		if (str == null || "".equals(str) || " ".equals(str)
				|| "null".equals(str) || "NULL".equals(str)) {
			return true;
		} else {
			return false;
		}
	}
	
	public static String trim(String str){
		if(str != null){
			str = str.trim().replaceAll("\\s","");
		}
		return str;
	}

	public static String strToUpper(String str) {
		String result = null;
		if (str != null && !str.equals("") && !"null".equals(str)) {
			result = str.toUpperCase();
		}
		return result;
	}

	/**
	 * 
	 * @author LEE
	 * @date:Jan 29, 2010 2:31:06 PM 功能：获得id加逗号 的id字符串.
	 * @param idsStr
	 * @return
	 */
	public static String getIdsStr(String idsStr) {
		if (idsStr.endsWith(",")) {
			idsStr = idsStr.substring(0, idsStr.length() - 1);
		} else if (isNull(idsStr)) {
			idsStr = "0";
		}
		return idsStr;
	}

	/**
	 * 
	 * Function:通过视频分类地址获得视频分类的名称 author:LEE 2011-11-9 下午01:00:28
	 * 
	 * @param categoryUrl
	 * @return
	 */
	public static String getCategoryFileNameFromCategoryUrl(String categoryUrl) {
		String result = "ERROR";
		if (isNotNull(categoryUrl)) {
			int index = categoryUrl.lastIndexOf("/");
			result = categoryUrl.substring(index + 1);
			if (result.contains("?")) {
				index = result.indexOf("?");
				result = result.substring(0, index);
			}
		}
		return result;
	}

	

	/**
	 * 
	 * Function: 把数字变为时间显示 author:LEE 2011-12-8 下午02:02:03
	 * 
	 * @param time
	 * @return
	 */
	public static String changeDigitalToDateStr(long time) {
		int hour = 60 * 60 * 1000;
		int min = 60 * 1000;
		int sec = 1000;
		String hourStr = "";
		String minStr = "";
		String secStr = "";
		String resultStr = "";
		if (time / hour >= 1) {
			hourStr = String.valueOf(time / hour) + "小时";
			time = time % hour;
			if (time / min > 1) {
				minStr = String.valueOf(time / min) + "分";
				time = time % min;
				secStr = time / sec + "秒";
			} else {
				minStr = "0分";
				secStr = String.valueOf(time / sec) + "秒";
			}
		} else if (time / min >= 1) {
			minStr = String.valueOf(time / min) + "分";
			time = time % min;
			secStr = time / sec + "秒";
		} else {
			secStr = String.valueOf(time / sec) + "秒";
		}
		resultStr = hourStr + minStr + secStr;
		return resultStr;
	}

	public static String getVideoIdFromImgFileName(String fileName) {
		String videoId = "0";
		if (isNotNull(fileName)) {
			String array[] = fileName.split("\\.");
			if (array.length > 1) {
				videoId = array[0];
			}
		}
		return videoId;
	}

	@SuppressWarnings({ "rawtypes", "unused" })
	public static void clearList(List l) {
		if (l != null) {
			for (Object obj : l) {
				obj = null;
			}
			l.clear();
		}
		System.gc();
	}

	@SuppressWarnings("rawtypes")
	public static void releaseObjectToNull(Object... objArray) {
		if (objArray != null) {
			for (int i = 0; i < objArray.length; i++) {
				if (objArray[i] != null) {
					if (objArray[i] instanceof List) {
						((List) objArray[i]).clear();
					}
					objArray[i] = null;
				}
			}
		}
		System.gc();
	}

	public static String getEncodeGB2312AsStr(String str) {
		String resultStr = "";
		try {
			if(isNotNull(str)) {
				resultStr = URLEncoder.encode(str, "gb2312");
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return resultStr;
	}

	/**
	 * @param in
	 * @return
	 * @description 根据InputStream得到返回的结果字符串
	 * @version 1.0
	 * @author 吕振威
	 * @date 2012-3-28 下午2:51:58
	 * @update 2012-3-28 下午2:51:58
	 */
	public static String convertStreamToString(InputStream in) {

		StringBuilder sb = new StringBuilder();   
        try {   
        	BufferedReader reader = new BufferedReader(new InputStreamReader(in));   
        	String line = null;   
            while ((line = reader.readLine()) != null) {   
                sb.append(line);   
            }   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
        	if(in != null){
	            try {   
	                in.close();   
	            } catch (IOException e) {   
	                e.printStackTrace();   
	            }   
        	}
        }   
        return sb.toString();
	}


	/**
	 * @param str
	 * @return
	 * @description 将字符串转为InputStream
	 * @version 1.0
	 * @author 吕振威
	 * @date 2012-3-28 下午4:02:20
	 * @update 2012-3-28 下午4:02:20
	 */
	public static InputStream convertStrToInputStream(String str) {
		ByteArrayInputStream stream = null;
		if (str != null && str.length() > 0) {
			stream = new ByteArrayInputStream(str.getBytes());
		}
		return stream;
	}

	/**
	 * @param str
	 * @return
	 * @description 字符串转换为utf-8编码
	 * @version 1.0
	 * @author zhangkun
	 * @date 2012-4-16 上午11:06:29
	 * @update 2012-4-16 上午11:06:29
	 */
	public static String getEncodeUTF8AsStr(String str) {
		String resultStr = "";
		try {
			if(isNotNull(str)) {
				resultStr = URLEncoder.encode(str, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return resultStr;
	}
	/**
	 * 
	 * @param str
	 * @return
	 * @description 去除换行符
	 * @version 1.0
	 * @author LEE
	 * @date 2012-5-23 下午6:35:15 
	 * @update 2012-5-23 下午6:35:15
	 */
	public static String removeNewLineSymbol(String str) {
		if(isNotNull(str)) {
			if(str.endsWith("\n")) {
				str = str.substring(0, str.length()-1);
			}
		}
		return str;
	}
	
	@SuppressWarnings("unused")
	public static boolean  judgeHasChinese(String content) {
		int chinese = 0;
		int english = 0;
		boolean isChinese = false;

		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < content.length(); i++) {
			String retContent = content.substring(i, i + 1);
			// 生成一个Pattern,同时编译一个正则表达式
			boolean isChina = retContent.matches("[\u4E00-\u9FA5]");
			if(isChina) {
				chinese++;
			}

			boolean isCapital = retContent.matches("[A-Z]");
			if(isCapital) {
				english++;
			}
			boolean isNum = retContent.matches("[0-9]");
			if(isNum) {
				english++;
			}
		}
		if(chinese >0) {
			isChinese = true;
		}else {
			isChinese = false;
		}
		
		return isChinese;
	}
	
	public static void propertyCopy(Object from,Object to) {
		Field[] fields = from.getClass().getFields();
		for (int i = 0; i < fields.length; i++) {
			String name = fields[i].getName();
			Field field;
			try {
				field = to.getClass().getField(name);
				field.set(to, fields[i].get(from));
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			
		}
	}
	public static String formatTime(long time){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:ms");//设置日期格式
		String mTm = df.format(new Date(time));
		return mTm;
	}


	public static String secondToString(int second) {
		int s = second % 60;
		int m = second / 60 % 60;
		int h = second / 60 / 60;
		return (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":"
				+ (s < 10 ? "0" + s : s);
	}
}
